# vim: ts=4:sw=4:syntax=perl

# Take all the args and update portal ... and then
# redirect to page in the LP parameter.
use gri_secmgr qw(get_user_name redirect_header);
use gri_user_alert_config;

sub mm_manage_alerts_process {
	my $str="";

	my $url_prefix=$::GRI_FRONTEND->get_url_prefix();
	my $v=get_user_name();
	#############################################################
	# If logged in as public then do not actually do anything!	#
	#############################################################
	if(! $v || $v eq "public") {
		if(exists($::PARAM{lp}) && $::PARAM{lp}) {
			redirect_header(path => hex_to_string($::PARAM{lp}));
		} else {
			my $l="$url_prefix$::ENV{SCRIPT_NAME}";
			redirect_header(path => $l);
			exit;
		}
		
	}
	my $alerts_dir=$::GRI_FRONTEND->get_global_directory("alerts");
	my $user_alerting;
	if(-f "$alerts_dir/$v.config.xml") {
		$user_alerting=new gri_user_alert_config("$alerts_dir/$v.config.xml");
	} else {
		$user_alerting=new gri_user_alert_config();
		$user_alerting->set_filename("$alerts_dir/$v.config.xml");
	} 
	$user_alerting->set_username($v);
	my $email=$user_alerting->get_email();
	if(!defined($email)) {
		$email=$::GRI_FRONTEND->get_user_email_address($v);
		if(!defined($email) || !length($email)) {
			html_error("Failed to resolve users email address for '$v'.\n",1);
		}
		$user_alerting->set_email($email);
	}
	
	my @R=();
	for (sort(keys(%::PARAM))) {
		if(/^AL_/) {
			my $val=$::PARAM{$_};
			my @F=split(/\~/,$val);
			push @R,@F;
		}
	}

	# Now write out the new file...
	$user_alerting->set_reports(@R);
	my $r=$user_alerting->write_file;
	if(!$r) {
		html_error("Failed to write file for user alerting: " . gri_user_alert_config::error(),1);
	}
	if(exists($::PARAM{lp}) && $::PARAM{lp}) {
		redirect_header(path => hex_to_string($::PARAM{lp}));
		exit;
	} else {
		my $l="$url_prefix$::ENV{SCRIPT_NAME}";
		redirect_header(path => $l);
		exit;
	}
}

